/*
 * @Author: EyeSklear 1814580085@qq.com
 * @Date: 2024-01-12 19:58:15
 * @LastEditors: EyeSklear 1814580085@qq.com
 * @LastEditTime: 2024-03-29 15:16:27
 * @FilePath: \Scene_Back\src\geojson\geojson.service.ts
 * @Description:
 *
 * Copyright (c) 2024 by EyeSklear , All Rights Reserved.
 */
import { BadRequestException, Inject, Injectable } from '@nestjs/common';
import { CreateGeojsonDto } from './dto/create-geojson.dto';
import { UpdateGeojsonDto } from './dto/update-geojson.dto';
import { Geojson } from './entities/geojson.entity';
import { Repository, In } from 'typeorm';
import { InjectRepository } from '@nestjs/typeorm';
import { WINSTON_LOGGER_TOKEN } from 'src/winston/winston.module';

export class GeojsonService {
  constructor(
    @InjectRepository(Geojson)
    private readonly geojsonRepository: Repository<Geojson>,
  ) {}

  @Inject(WINSTON_LOGGER_TOKEN)
  private logger;

  async createItem(createGeojsonDto: CreateGeojsonDto) {
    const geojson = this.geojsonRepository.create(createGeojsonDto);
    const insertRes = await this.geojsonRepository.insert(geojson);
    return insertRes.raw;
  }

  async createItemForScript(createGeojsonDto: CreateGeojsonDto) {
    const geojson = this.geojsonRepository.create(createGeojsonDto);
    const insertRes = await this.geojsonRepository.insert(geojson);
    return insertRes.raw[0].id;
  }

  async findAll(): Promise<Geojson[]> {
    return this.geojsonRepository.find();
  }

  async findByIds(ids: string[]): Promise<Geojson[]> {
    return this.geojsonRepository.find({
      where: {
        id: In(ids), // 使用TypeORM的In操作符
      },
    });
  }

  async findOne(id: string): Promise<Geojson> {
    return this.geojsonRepository.findOne({ where: { id: id } });
  }

  async update(id: string, updateGeojsonDto: UpdateGeojsonDto) {
    const oldGeojson = await this.geojsonRepository.findOne({
      where: { id: id },
    });
    if (!oldGeojson) {
      return '地图矢量条目不存在';
    }
    try {
      const updateGeojson = this.geojsonRepository.merge(
        oldGeojson,
        updateGeojsonDto,
      );
      await this.geojsonRepository.save(updateGeojson);
      return '修改地图矢量条目属性成功!';
    } catch (err) {
      this.logger.error(`更新地图矢量条目失败${err}`,`${GeojsonService.name}-${this.update.name}`)
      throw new BadRequestException('更新地图矢量条目失败');
    }
  }

  async remove(id: string) {
    const result = await this.geojsonRepository.delete({ id: id });
    if (result.affected && result.affected > 0) {
      return `成功删除 ${result.affected} 条记录`;
    } else {
      return `未找到匹配的记录，没有进行删除操作`;
    }
  }
}
